package com.winter.boot.web.handler;

import com.winter.boot.WinterApplication;
import com.winter.boot.config.BeanFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.lang.reflect.Method;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    // k,v : /user/users , controller.method 这两个k,v组合放到一个map中
    private static final Map<String, String> handlerMap = new ConcurrentHashMap<>();
    private final BeanFactory beanFactory = WinterApplication.getApplicationContext().getDefaultBeanFactory();

    public static void addHandler(String key, String value) {
        handlerMap.put(key, value);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) {
        if (httpObject instanceof HttpRequest) {
            try {
                HttpRequest httpRequest = (HttpRequest) httpObject;
                //3.获取uri, 过滤指定的资源
                URI uri = new URI(httpRequest.uri());
                if ("/favicon.ico".equals(uri.getPath())) {//过滤掉静态资源
                    return;
                }
                String path = uri.getPath(); //请求路径/**/**
                String query = uri.getQuery(); //请求参数
                // TODO: 2022/10/19 query 参数列表转成数组

                String fullName = handlerMap.get(path);
                if (fullName == null) {
                    DefaultFullHttpResponse response = new DefaultFullHttpResponse(
                            HttpVersion.HTTP_1_1,
                            HttpResponseStatus.NOT_FOUND,
                            Unpooled.copiedBuffer("false", CharsetUtil.UTF_8));
                    ctx.writeAndFlush(response);
                    return; //404
                }
                String beanName = fullName.substring(0, fullName.lastIndexOf('.'));
                String method = fullName.substring(fullName.lastIndexOf(".") + 1);
                Object bean = beanFactory.getBean(beanName);
                Class<?>[] classes = beanFactory.getParams(beanName).toArray(new Class[0]);
                Method method1 = bean.getClass().getMethod(method, classes);
                // TODO: 2022/10/19 放入query格式化好的参数列表
                Object result = method1.invoke(bean,null);

                ByteBuf content = Unpooled.copiedBuffer(result.toString(), CharsetUtil.UTF_8);
                FullHttpResponse response = new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1,
                        HttpResponseStatus.OK,
                        content);
                //4.设置响应头信息-响应格式
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                //5.设置响应头信息-响应数据长度
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

                //6.将构建好 response返回
                ctx.writeAndFlush(response);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}
